// import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getRoleList, getRoleUpdate, getRoleDelete } from "@/api/user";
import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { delay, useWatermark } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { sessionKey } from "@/utils/auth";
import type { PaginationProps, LoadingConfig } from "@pureadmin/table";
import { storageSession } from "@pureadmin/utils";
import { initRouter } from "@/router/utils";
import * as CryptoJS from "crypto-js";
import { getSessionKey } from "@/utils/auth";
import { reactive, ref, computed, onMounted, inject } from "vue";
import { roleList, delAsyncRoutes } from "@/api/routes";
import { companyDelete } from "@/api/companyList";
import { getAdminManageList, getAdminManageListInfo } from "@/api/loanListPage";
console.log(import.meta.env.VITE_PROXY_TARGET);

const baseUrl = window.location.origin;
export function useRole(waterRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const router = useRouter();
  const refresh: any = inject("reload");
  interface StorageConfigs {
    role_id: number;
  }
  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 30],
    total: 0,
    align: "right",
    background: true,
    small: false
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "管理员昵称",
      prop: "admin_nick",
      minWidth: 200
    },
    {
      label: "公司名",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "法人名称",
      prop: "legal_name",
      minWidth: 150
    },
    {
      label: "类型名称",
      prop: "type_name",
      minWidth: 150
    },
    {
      label: "抵押担保名",
      minWidth: 100,
      prop: "collateral_name"
    },
    {
      label: "贷款银行",
      prop: "loan_bank",
      minWidth: 150
    },
    {
      label: "贷款金额",
      minWidth: 180,
      prop: "loan_money"
    },
    {
      label: "利率（%）",
      minWidth: 180,
      prop: "interest_rate"
    },
    {
      label: "贷款期限(年)",
      minWidth: 180,
      prop: "loan_year"
    },
    {
      label: "贷款开始时间",
      minWidth: 180,
      prop: "loan_start"
    },
    {
      label: "贷款结束时间",
      minWidth: 180,
      prop: "loan_over"
    },
    {
      label: "授托公司",
      minWidth: 180,
      prop: "entrusting_company"
    },
    {
      label: "使用单位",
      minWidth: 180,
      prop: "building_user"
    },
    {
      label: "最高额度",
      minWidth: 180,
      prop: "maximum_amount",
      formatter(row) {
        const rowStr = row.maximum_amount == 1 ? "是" : "否";
        return rowStr;
      }
    },
    {
      label: "可用贷款余额",
      minWidth: 180,
      prop: "usable_balance"
    },
    {
      label: "授信额度",
      minWidth: 180,
      prop: "credit_limit"
    },
    {
      label: "永信额度",
      minWidth: 180,
      prop: "use_limit"
    },
    {
      label: "守信余额",
      minWidth: 180,
      prop: "credit_balance"
    },
    {
      label: "备注",
      minWidth: 180,
      prop: "notes"
    },
    {
      label: "图片资料",
      minWidth: 180,
      prop: "image",
      formatter: row => {
        // let image=JSON.parse(JSON.stringify(row)).image
        // let url=`${image}`
        // console.log(JSON.parse(JSON.stringify(row)).image,'image',url)
        return (
          <div>
            <img style="width: 100px; height: 100px" src={url} />
          </div>
        );
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  function onChange({ row, index }) {
    console.log(row, index);
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>人员吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        const rowValue = {
          admin_id: row.admin_id,
          admin_status: row.admin_status
        };
        const rowJson = JSON.stringify(rowValue);
        // 对JSON字符串进行Base64加密
        // const encryptedFormIsRef = CryptoJS.enc.Base64.stringify(
        //   CryptoJS.enc.Utf8.parse(rowJson)
        // );
        // const rowtype = {
        //   value: encryptedFormIsRef
        // };
        const res = getUpdate(rowValue);
        console.log(res);
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改人员状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }
  /**修改角色状态 */
  async function handleUpdate(row) {
    const res = getRoleUpdate(row);
    console.log(row, res);
  }
  /**删除角色 */
  async function handleDelete(row) {
    const idname = { id: row.id };
    // const idnameJson = JSON.stringify(idname);
    // const idnameBase64 = CryptoJS.enc.Base64.stringify(
    //   CryptoJS.enc.Utf8.parse(idnameJson)
    // );
    // const idnameValue = {
    //   value: idnameBase64
    // };
    const res = await companyDelete(idname);
    if (res.code == 200) {
      message("删除成功", { type: "success" });
      refresh();
    } else {
      message(res.msg, { type: "error" });
    }
  }
  function handleaddUser() {
    console.log("dshfjskdhf");
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagesize.value = val;
    getList();
  }

  function handleCurrentChange(val: number) {
    page.value = val;
    getList();
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
  }

  //搜索
  async function onSearch(formIs) {
    loading.value = true;
    const params = {
      ...formIs,
      page: page.value,
      pagesize: pagesize.value
    };
    const { data } = await getAdminManageList(params);
    dataList.value = data.data;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  const pagesize = ref(10);
  const page = ref(1);
  //获取数据
  async function getList() {
    const params = {
      pagesize: pagesize.value,
      page: page.value,
      name: "",
      tax_level: "",
      legal: ""
    };
    const res = await getAdminManageListInfo(params);
    if (res.code === 200) {
      dataList.value = res.data.data;
      console.log(dataList.value.length, "参数的");
      pagination.total = res.data.total;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } else {
      message(res.msg, { type: "error" });
    }
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    location.reload();
  };

  onMounted(() => {
    delay().then(() => {
      // https://pure-admin-utils.netlify.app/hooks/useWatermark/useWatermark.html
      const { setWatermark } = useWatermark(
        waterRef.value.getTableDoms().tableWrapper
      );
      //水印
      setWatermark("后台项目", {
        font: "16px Microsoft YaHei",
        globalAlpha: 0.8,
        forever: true,
        width: 252,
        height: 80
      });
    });
    getList();
  });

  return {
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleaddUser,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onCurrentChange
  };
}
